package com.xiangying.aspect;

import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;

/**
 * 用于记录日志
 * @author luolihong
 *
 */
@Aspect
@Component
public class LogAspect {

	private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);
	
	@Pointcut("execution(public * com.xiangying.controller..*(..))")
	public void log(){
		logger.info("打印日志");
	}
	
	@Before("log()")
	public void doBefore(JoinPoint joinPoint){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		
		// 请求路径
		logger.info("reques-->url = " + request.getRequestURL());
		// 请求方式
		logger.info("request-->method = " + request.getMethod());
		// ip地址
		logger.info("request-->ip = " + request.getRemoteAddr());
		// 请求方法
		logger.info("request-->class_method = " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		// 请求参数
		logger.info("request-->params\n");
		StringBuffer parameter = new StringBuffer();
		Map<String, String[]> parameterMap = request.getParameterMap();
		if (parameterMap != null) {
			for (Entry<String, String[]> entry : parameterMap.entrySet()) {
				String parameterName = entry.getKey();
				String[] parameterValues = entry.getValue();
				if (parameterValues != null) {
					for (String parameterValue : parameterValues) {
						parameter.append(parameterName + " = " + parameterValue + "\n");
					}
				}
			}
		}
		logger.info(parameter.toString());
	}
	
	@After("log()")
	public void doAfter(){
		logger.info("-------------after----------------");
	}
	
	@AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
		if(object != null) {
			String resultJson = JSONObject.toJSONString(object);
			logger.info("response = " + resultJson);
		}
    }
}
